using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EasyCommerce.BLL;
using EasyCommerce.DAL;
using System.Collections.Generic;
using CodeWork.Library.Data;
using CodeWork.Library.Web;
using System.Data.SqlTypes;
using CodeWork.Library;

public partial class admin_SiteUserList : BasePage
{
	private SecurityLevel _securityLevel = SecurityLevel.One;
	
    public string GrvSiteUserListSortOrder
    {
        get
        {
            string orderBy = " id ";

            if (ViewState["orderBy"] != null)
                orderBy = ViewState["orderBy"].ToString();
            else
                ViewState["orderBy"] = orderBy;

            return orderBy;
        }
        set { ViewState["orderBy"] = value; }
    }

    public int GrvSiteUserListStartRow
    {
        get
        {
            int startRow = 0;

            if (ViewState["startRow"] != null)
                int.TryParse(ViewState["startRow"].ToString(), out startRow);
            else
                ViewState["startRow"] = startRow;

            return startRow;
        }
        set { ViewState["startRow"] = value; }
    }

    private int _totalItems;

    public int TotalItems
    {
        get 
        { 
            SiteUser siteUser = new SiteUser();
            this._totalItems = siteUser.LoadCount(PrepareFilterConditions());
            return this._totalItems; 
        }
        set { this._totalItems = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptInclude("ApplicationCommon", "../javascripts/ApplicationCommon.js");

        if (!IsPostBack)
        {
            try
            {
                BindGrid();
            }
            catch (Exception ex)
            {
                LoadMessage = CommonMessage.CommonErrorMessage;
            }
        }
    }

    private List<Condition> PrepareFilterConditions()
    {
        List<Condition> conditions = new List<Condition>();

        string userName = Security.BindStringInput(tbxUserName.Text, _securityLevel);
		string userPassword = Security.BindStringInput(tbxUserPassword.Text, _securityLevel);
		string emailAddress = Security.BindStringInput(tbxEmailAddress.Text, _securityLevel);
		string confirmationCode = Security.BindStringInput(tbxConfirmationCode.Text, _securityLevel);
		string securityQuestion = Security.BindStringInput(tbxSecurityQuestion.Text, _securityLevel);
		string securityAnswer = Security.BindStringInput(tbxSecurityAnswer.Text, _securityLevel);
		string registerIp = Security.BindStringInput(tbxRegisterIp.Text, _securityLevel);
		conditions.Add(new Condition("user_name", ConditionOperator.Like, userName, JoinOperator.FirstValue));
		conditions.Add(new Condition("user_password", ConditionOperator.Like, userPassword, JoinOperator.And));
		conditions.Add(new Condition("email_address", ConditionOperator.Like, emailAddress, JoinOperator.And));
		conditions.Add(new Condition("confirmation_code", ConditionOperator.Like, confirmationCode, JoinOperator.And));
		conditions.Add(new Condition("security_question", ConditionOperator.Like, securityQuestion, JoinOperator.And));
		conditions.Add(new Condition("security_answer", ConditionOperator.Like, securityAnswer, JoinOperator.And));
		conditions.Add(new Condition("register_ip", ConditionOperator.Like, registerIp, JoinOperator.And));

        return conditions;
    }

    private void BindGrid()
    { 
        SiteUser siteUser = new SiteUser();
        List<Condition> conditions = PrepareFilterConditions();

        string orderBy = GrvSiteUserListSortOrder;
        int startRow = GrvSiteUserListStartRow;
        int pageSize = grvSiteUserList.PageSize;

        List<SiteUser> siteUsers = siteUser.Load(orderBy, startRow, pageSize, conditions);

		if (siteUsers.Count == 0)
        {
            GrvSiteUserListStartRow -= grvSiteUserList.PageSize;
            if (GrvSiteUserListStartRow < 0)
                GrvSiteUserListStartRow = 0;

            siteUsers = siteUser.Load(orderBy, GrvSiteUserListStartRow, pageSize, conditions);
        }

        grvSiteUserList.DataSource = siteUsers;
        grvSiteUserList.DataBind();
        
        BindPager();
        
        string start = (GrvSiteUserListStartRow + 1).ToString();
        string end = ((GrvSiteUserListStartRow + grvSiteUserList.PageSize) > TotalItems ? TotalItems.ToString() : (GrvSiteUserListStartRow + grvSiteUserList.PageSize).ToString());
        if (TotalItems == 0)
            start = "0";
        pagerLabel.Text = "Showing " + start + " to " + end + " of " + TotalItems.ToString();
    }
    
    private void BindPager()
    {
        pager.DataSource = Utility.PreparePagingData(TotalItems, grvSiteUserList.PageSize);
        pager.DataBind();
    }

    protected void grvSiteUserList_RowCommand(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "editCommand")
                Response.Redirect("siteuseredit.aspx?id=" + e.CommandArgument.ToString());
            else if (e.CommandName == "deleteCommand")
            {
                SiteUser.Delete(Convert.ToInt32(e.CommandArgument));
                BindGrid();
            }
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void grvSiteUserList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox selectAll = (CheckBox)e.Row.FindControl("selectAll");
                selectAll.Attributes.Add("onclick", "SelectAll('" + grvSiteUserList.ClientID + "','" + selectAll.ClientID + "')");
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Int32 id = (Int32)grvSiteUserList.DataKeys[e.Row.RowIndex].Value;

                ImageButton editButton = (ImageButton)e.Row.FindControl("editButton");
                editButton.CommandArgument = id.ToString();
                editButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/row_edit.gif";

                ImageButton deleteButton = (ImageButton)e.Row.FindControl("deleteButton");
                deleteButton.CommandArgument = id.ToString();
                deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete?');");
                deleteButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/row_delete.gif";
            }
        }
        catch(Exception ex)
        {
            LoadMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void AddNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("siteuseredit.aspx");
    }

    protected void Delete_Selected(object sender, EventArgs e)
    {
        try
        {
            GridViewRowCollection grvSiteUserListRows = grvSiteUserList.Rows;
            List<int> idToDelete = new List<int>();

            foreach (GridViewRow row in grvSiteUserListRows)
            {
                CheckBox rowSelection = (CheckBox)row.FindControl("rowSelect");

                if (rowSelection.Checked)
                    idToDelete.Add((int)grvSiteUserList.DataKeys[row.RowIndex].Value);
            }

            if (SiteUser.Delete(idToDelete))
                BindGrid();
            else
                ResponseMessage = CommonMessage.DeleteErrorMessage;
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Filter_Click(object sender, EventArgs e)
    {
        try
        {
            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void grvSiteUserList_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(GrvSiteUserListSortOrder))
            {
                if (GrvSiteUserListSortOrder == e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Ascending))
                    GrvSiteUserListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Descending);
                else if (GrvSiteUserListSortOrder == e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Descending))
                    GrvSiteUserListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Ascending);
                else
                    GrvSiteUserListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(e.SortDirection);
            }
            else
                GrvSiteUserListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(e.SortDirection);

            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Pager_Command(object sender, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "first" || e.CommandName == "last" || e.CommandName == "paging")
            {
                GrvSiteUserListStartRow = Convert.ToInt32(e.CommandArgument) * grvSiteUserList.PageSize;
            }
            else if (e.CommandName == "prev")
            {
                GrvSiteUserListStartRow -= grvSiteUserList.PageSize;
                if (GrvSiteUserListStartRow < 0)
                    GrvSiteUserListStartRow = 0;
            }
            else if (e.CommandName == "next")
            {
                GrvSiteUserListStartRow += grvSiteUserList.PageSize;
                if (GrvSiteUserListStartRow > ((TotalItems-1) / grvSiteUserList.PageSize) * grvSiteUserList.PageSize)
                    GrvSiteUserListStartRow = ((TotalItems-1) / grvSiteUserList.PageSize) * grvSiteUserList.PageSize;
            }
            
            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Pager_DataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                ImageButton firstButton = (ImageButton)e.Item.FindControl("btnFirst");
                firstButton.CommandArgument = "0";
                firstButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/first-page.png";
                ImageButton prevButton = (ImageButton)e.Item.FindControl("btnPrev");
                prevButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/prev-page.png";
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                ImageButton lastButton = (ImageButton)e.Item.FindControl("btnLast");
                lastButton.CommandArgument = ((TotalItems-1) / grvSiteUserList.PageSize).ToString();
                lastButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/last-page.png";
                ImageButton nextButton = (ImageButton)e.Item.FindControl("btnNext");
                nextButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/next-page.png";
            }
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }
}
